<template>
	<view class="skills-page">
		<nav-header :title="pageTitle"></nav-header>

		<view class="content" :style="{ marginTop: statusBarHeight + 44 + 'px' }">
			<view class="page-title">技能特长</view>
			<view class="subtitle">添加你掌握的技能和专长</view>

			<!-- Skills Section -->
			<view class="skills-section">
				<view class="section-header">
					<view class="header-row">
						<text class="title">我的技能</text>
						<button class="generate-btn" @click="handleGenerateSkills">
							<text class="generate-icon">✨</text>AI生成
						</button>
					</view>
					<text class="subtitle">请选择你掌握的技能，也可以添加自定义技能</text>
				</view>

				<!-- Skills Tags -->
				<view class="tags-container">
					<!-- :class="{ 'active': skill.selected }" -->
					<view v-for="(skill, index) in skillsList" :key="index" class="tag" @click="toggleSkill(index)">
						<text>{{ skill.name }}</text>
						<text v-if="skill.selected" class="remove-icon">×</text>
					</view>

					<!-- Add Custom Skill -->
					<view class="tag add-tag" @click="showAddSkillInput = true" v-if="!showAddSkillInput">
						<text class="add-icon">+</text>
						<text>添加技能</text>
					</view>

					<!-- Custom Skill Input -->
					<view class="add-skill-input" v-if="showAddSkillInput">
						<input type="text" v-model="newSkill" placeholder="输入技能名称" :focus="showAddSkillInput"
							@blur="handleInputBlur" @confirm="addCustomSkill" maxlength="20" />
						<text class="confirm-btn" @click="addCustomSkill">添加</text>
					</view>
				</view>
			</view>

			<!-- Skill Level Section -->
			<view class="skills-section" v-if="selectedSkills.length > 0">
				<view class="section-header">
					<text class="title">技能评级</text>
					<text class="subtitle">拖动滑块设置各项技能的熟练程度</text>
				</view>

				<!-- Skill Levels -->
				<view class="skill-levels">
					<view v-for="skill in selectedSkills" :key="skill.name" class="skill-level-item">
						<view class="skill-name">{{ skill.name }}</view>
						<view class="skill-slider-container" v-if="skillType!='professional'">
							<slider :value="skill.level" min="1" max="5" :block-size="24" activeColor="#5ac725"
								backgroundColor="#e9e9e9"
								@change="(e) => updateSkillLevel(skill.name, e.detail.value)" />
							<view class="level-text">{{ getLevelText(skill.level) }}</view>
						</view>
					</view>
				</view>
			</view>

			<!-- Professional Summary Section -->
			<!--      <view class="skills-section">
        <view class="section-header">
          <text class="title">专业概述</text>
          <text class="subtitle">简短介绍你的专业背景、技能专长或职业目标</text>
        </view>
        
        <view class="summary-container">
          <textarea
            class="summary-textarea"
            v-model="summary"
            placeholder="例如：3年前端开发经验，熟悉Vue.js、React等框架，擅长构建高性能的用户界面和响应式布局..."
            maxlength="500"
          ></textarea>
          <text class="word-count">{{ summary.length }}/500</text>
        </view>
      </view> -->
		</view>

		<!-- Save Button -->
		<view class="bottom">
			<!-- Delete Button -->
			<!-- <view class="delete-action" v-if="!isAdding">
				<button class="delete-btn" @click="confirmDeleteSkill">删除</button>
			</view> -->
			<!-- Save Button -->
			<view class="action-bar">
				<button class="save-btn" @click="saveSkills">保存</button>
			</view>
		</view>

		<!-- Delete Confirmation -->
		<uni-popup ref="deleteConfirmPopup" type="dialog">
			<uni-popup-dialog title="删除确认" content="确定要删除这条技能记录吗？删除后将无法恢复。" :beforeClose="true"
				@confirm="deleteSkill" @close="closeDeleteConfirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		useResumeStore
	} from '@/store/resume.js'
	import NavHeader from '@/components/nav-header.vue'
	import {
		onLoad
	} from '@dcloudio/uni-app' // 新增引入
	import {
		getProfessionalSkillList,
		getProfessionalSkillDetail,
		addProfessionalSkill,
		updateProfessionalSkill,
		deleteProfessionalSkill,
		getQualificationCertificateList,
		getQualificationCertificateDetail,
		addQualificationCertificate,
		updateQualificationCertificate,
		deleteQualificationCertificate,
		generateQualificationCertificate,
		generateProfessionalSkills
	} from '@/api/edit/skill.js'

	const statusBarHeight = ref(20)
	const showAddSkillInput = ref(false)
	const newSkill = ref('')
	const summary = ref('')
	const skillType = ref('general') // 'general' or 'professional'
	const pageTitle = ref('技能特长')
	const resumeStore = useResumeStore()
	const isAdding = ref(true)
	const currentId = ref(null)
	const deleteConfirmPopup = ref(null)

	// 预定义的常用技能列表
	const commonSkills = {
		general: [
			'JavaScript', 'CSS', 'HTML', 'Vue.js', 'React',
			'Angular', 'Node.js', 'TypeScript', 'Python',
			'Java', 'C++', 'C#', 'PHP', 'Swift', 'Kotlin',
			'SQL', 'MongoDB', 'Git', 'Docker', 'AWS',
			'UI设计', 'UX设计', '产品设计', '项目管理', 'Scrum',
			'数据分析', '机器学习', '人工智能', '大数据', '云计算'
		],
		professional: [
			'CET-4', 'CET-6', 'IELTS', 'TOEFL', '托业',
			'PMP', 'CPA', 'CFA', 'ACCA', 'FRM',
			'律师资格证', '会计证', '教师资格证', '医师资格证', '建筑师证',
			'驾驶执照', '健身教练证', '营养师证', '心理咨询师', '导游证'
		]
	}

	const skillsList = ref([])

	// 初始化技能列表
	const initSkillsList = () => {
		// 获取当前类型的预定义技能
		const predefinedSkills = commonSkills[skillType.value] || commonSkills.general

		// 先添加预定义的技能
		skillsList.value = predefinedSkills.map(name => ({
			name,
			selected: false,
			level: 3 // 默认为中等水平
		}))

		// 获取对应类型的技能数据
		const savedSkills = skillType.value === 'professional' ?
			resumeStore.professional || [] :
			resumeStore.skills || []

		// 如果已有保存的技能，标记为已选
		if (savedSkills.length > 0) {
			savedSkills.forEach(savedSkill => {
				// 查找该技能是否在预定义列表中
				const existingSkill = skillsList.value.find(s => s.name === savedSkill.name)

				if (existingSkill) {
					// 如果存在，标记为已选择并更新级别
					existingSkill.selected = true
					existingSkill.level = savedSkill.level
				} else {
					// 如果不存在，添加到技能列表
					skillsList.value.push({
						name: savedSkill.name,
						selected: true,
						level: savedSkill.level
					})
				}
			})
		}
	}

	// 已选技能列表
	const selectedSkills = computed(() => {
		return skillsList.value.filter(skill => skill.selected)
	})


	onMounted(async () => {
		const systemInfo = uni.getSystemInfoSync()
		statusBarHeight.value = systemInfo.statusBarHeight

		await generateSkills(0);

		// 根据技能类型加载数据
		await loadSkillsData();
	})

	onLoad((options) => {
		if (options.type === 'professional') {
			skillType.value = 'professional'
			pageTitle.value = '资格证书'
		}

		if (options.index) {
			isAdding.value = false
			currentId.value = options.index
		} else {
			isAdding.value = true
		}

		
	})

	// 加载技能数据
	const loadSkillsData = async () => {
		try {
			uni.showLoading({
				title: '加载中...'
			});
			
			let res;
			
			if (skillType.value === 'professional') {
				// 获取资格证书列表
				res = await getQualificationCertificateList({resumeId:resumeStore.resumeId,});
			} else {
				// 获取专业技能列表
				res = await getProfessionalSkillList({resumeId:resumeStore.resumeId,});
			}
			
			if (res && res.code === 200 && res.rows && res.rows.length > 0) {
				// 存在数据，设置为编辑模式
				isAdding.value = false;
				
				// 初始化技能列表
				initSkillsWithData(res.rows);
			} else {
				// 没有数据，设置为新增模式
				isAdding.value = true;
			}
		} catch (error) {
			console.error('加载技能数据失败', error);
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	}
	
	// 使用后端数据初始化技能列表
	const initSkillsWithData = (data) => {

		console.log('initSkillsWithData', skillsList.value);
		
		// 根据不同的技能类型处理数据
		if (skillType.value === 'professional') {
			// 资格证书数据处理
			data.forEach(item => {
				// 查找该技能是否在预定义列表中
				const existingSkill = skillsList.value.find(s => s.name === item.certificateName);
				
				if (existingSkill) {
					// 如果存在，标记为已选择并设置ID
					existingSkill.selected = true;
					existingSkill.id = item.id;
				} else {
					// 如果不存在，添加到技能列表
					skillsList.value.push({
						name: item.certificateName,
						selected: true,
						id: item.id
					});
				}
			});
		} else {
			// 专业技能数据处理
			data.forEach(item => {
				// 查找该技能是否在预定义列表中
				const existingSkill = skillsList.value.find(s => s.name === item.skillName);
				
				if (existingSkill) {
					// 如果存在，标记为已选择并更新级别和ID
					existingSkill.selected = true;
					existingSkill.level = item.proficiency || 3;
					existingSkill.id = item.id;
				} else {
					// 如果不存在，添加到技能列表
					skillsList.value.push({
						name: item.skillName,
						selected: true,
						level: item.proficiency || 3,
						id: item.id
					});
				}
			});
		}
		console.log('initSkillsWithData最终结果', skillsList.value);
	}

	const toggleSkill = (index) => {
		skillsList.value[index].selected = !skillsList.value[index].selected
	}

	const addCustomSkill = async () => {
		if (newSkill.value.trim()) {
			const existingSkill = skillsList.value.find(s => s.name.toLowerCase() === newSkill.value.trim()
				.toLowerCase())

			if (existingSkill) {
				// 如果存在，标记为已选择
				existingSkill.selected = true

				uni.showToast({
					title: '该技能已存在',
					icon: 'none'
				})
			} else {
				// 如果不存在，添加到列表
				skillsList.value.push({
					name: newSkill.value.trim(),
					selected: true,
					level: 3 // 默认为中等水平
				})
			}

			// 重置输入
			newSkill.value = ''
			showAddSkillInput.value = false
		} else {
			showAddSkillInput.value = false
		}
	}

	const handleInputBlur = () => {
		if (newSkill.value.trim()) {
			addCustomSkill()
		} else {
			showAddSkillInput.value = false
		}
	}

	const updateSkillLevel = async (skillName, level) => {
		const skill = skillsList.value.find(s => s.name === skillName)
		if (skill) {
			skill.level = level
			let res
			if (skillType.value === 'professional') {
				res = await updateQualificationCertificate({
					id: skill.id,
					name: skill.name,
					level
				})
			} else {
				res = await updateProfessionalSkill({
					id: skill.id,
					name: skill.name,
					level
				})
			}
			if (res && res.code === 200) {
				uni.showToast({
					title: '已更新',
					icon: 'success'
				})
			}
		}
	}

	const getLevelText = (level) => {
		const levelTexts = ['', '入门', '基础', '熟练', '精通', '专家']
		return levelTexts[level] || '熟练'
	}

	const saveSkills = async () => {
		// 只保存已选中的技能
		const selected = skillsList.value.filter(skill => skill.selected);
		
		try {
			uni.showLoading({
				title: '保存中...'
			});
			
			// 分类处理数据
			if (skillType.value === 'professional') {
				// 处理资格证书
				for (const skill of selected) {
					const params = {
						resumeId: resumeStore.resumeId,
						certificateName: skill.name
					};
					
					if (skill.id) {
						// 更新
						await updateQualificationCertificate({
							...params,
							id: skill.id
						});
					} else {
						// 添加
						await addQualificationCertificate(params);
					}
					
					// 避免请求过于频繁
					await new Promise(resolve => setTimeout(resolve, 300));
				}
				
				// 处理已取消选择的技能（需要删除）
				const deselected = skillsList.value.filter(skill => !skill.selected && skill.id);
				for (const skill of deselected) {
					await deleteQualificationCertificate(skill.id);
					await new Promise(resolve => setTimeout(resolve, 300));
				}
			} else {
				// 处理专业技能
				for (const skill of selected) {
					const params = {
						resumeId: resumeStore.resumeId,
						skillName: skill.name,
						proficiency: skill.level
					};
					
					if (skill.id) {
						// 更新
						await updateProfessionalSkill({
							...params,
							id: skill.id
						});
					} else {
						// 添加
						await addProfessionalSkill(params);
					}
					
					// 避免请求过于频繁
					await new Promise(resolve => setTimeout(resolve, 300));
				}
				
				// 处理已取消选择的技能（需要删除）
				const deselected = skillsList.value.filter(skill => !skill.selected && skill.id);
				for (const skill of deselected) {
					await deleteProfessionalSkill(skill.id);
					await new Promise(resolve => setTimeout(resolve, 300));
				}
			}
			
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			});
			
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		} catch (error) {
			console.error('保存技能失败', error);
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	}

	// 确认删除弹窗
	const confirmDeleteSkill = () => {
		deleteConfirmPopup.value.open()
	}
	
	// 关闭删除确认弹窗
	const closeDeleteConfirm = () => {
		uni.hideLoading()
		deleteConfirmPopup.value.close()
	}
	
	// 删除技能
	const deleteSkill = async () => {
		if (!currentId.value) return
		try {
			uni.showLoading({
				title: '删除中...'
			})
			let res
			if (skillType.value === 'professional') {
				res = await deleteQualificationCertificate(currentId.value)
			} else {
				res = await deleteProfessionalSkill(currentId.value)
			}
			
			if (res.code === 200) {
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: res.msg || '删除失败',
					icon: 'none'
				})
			}
		} catch (e) {
			uni.showToast({
				title: '删除失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	// 处理生成技能按钮点击
	const handleGenerateSkills = () => {
		generateSkills(1);
	}

	// 生成技能
	const generateSkills = async (status) => {
		try {
			uni.showLoading({
				title: '生成中...'
			});
			
			let res;
			
			if (skillType.value === 'professional') {
				// 生成资格证书
				res = await generateQualificationCertificate({	
					resumeId: resumeStore.resumeId,
					status: status
				});
			} else {
				// 生成专业技能
				res = await generateProfessionalSkills({
					resumeId: resumeStore.resumeId,
					status: status
				});
			}
			
			if (res && res.code === 200 && res.data) {
				// 成功生成技能
				if (skillType.value === 'professional') {
					// 处理资格证书数据
					res.data.forEach(item => {
						addSkillToList(item.certificateName);
					});
				} else {
					// 处理专业技能数据
					res.data.forEach(item => {
						addSkillToList(item.skillName);
					});
				}
				
				uni.showToast({
					title: '生成成功',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: res?.msg || '生成失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('生成技能失败', error);
			uni.showToast({
				title: '生成失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	}

	// 将技能添加到列表
	const addSkillToList = (skillName) => {
		if (!skillName) return;

		// 查找技能是否已存在
		const existingIndex = skillsList.value.findIndex(s => 
			s.name.toLowerCase() === skillName.toLowerCase()
		);
		
		if (existingIndex < 0) {
			// 如果不存在，添加到列表
			skillsList.value.push({
				name: skillName,
				selected: false,
				level: 3 // 默认为中等水平
			});
		}
	};
</script>

<style lang="scss" scoped>
	.skills-page {
		min-height: 100vh;
		background-color: #FFFFFF;
		padding-bottom: 70px;

		.content {
			padding: 20px;

			.page-title {
				font-size: 24px;
				font-weight: bold;
				color: #333;
				margin-bottom: 6px;
			}

			.subtitle {
				font-size: 14px;
				color: #999;
				margin-bottom: 24px;
			}

			.skills-section {
				margin-bottom: 24px;

				.section-header {
					margin-bottom: 16px;

					.header-row {
						display: flex;
						align-items: center;
						justify-content: space-between;
						margin-bottom: 4px;
					}

					.title {
						font-size: 16px;
						font-weight: 500;
						color: #333;
						display: block;
					}

					.subtitle {
						font-size: 14px;
						color: #999;
						margin-bottom: 0;
					}
					
					.generate-btn {
						display: flex;
						align-items: center;
						justify-content: center;
						padding: 0 12px;
						height: 30px;
						background-color: #f0f7ff;
						border: 1px solid #d0e6ff;
						border-radius: 15px;
						font-size: 13px;
						color: #4080ff;
						line-height: 1;
						margin: 0;
						
						.generate-icon {
							margin-right: 4px;
							font-size: 14px;
						}
					}
				}

				.tags-container {
					display: flex;
					flex-wrap: wrap;

					.tag {
						height: 36px;
						padding: 0 12px;
						background-color: #f5f5f5;
						border-radius: 18px;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 10px;
						margin-bottom: 10px;
						font-size: 14px;
						color: #666;

						&.active {
							background-color: #e6f7e1;
							color: #5ac725;

							.remove-icon {
								margin-left: 5px;
								font-size: 16px;
							}
						}

						&.add-tag {
							border: 1px dashed #ccc;
							background-color: transparent;

							.add-icon {
								margin-right: 3px;
								font-size: 16px;
							}
						}
					}

					.add-skill-input {
						display: flex;
						align-items: center;
						height: 36px;
						border: 1px solid #ddd;
						border-radius: 18px;
						padding: 0 12px;
						margin-bottom: 10px;

						input {
							flex: 1;
							height: 100%;
							font-size: 14px;
						}

						.confirm-btn {
							color: #5ac725;
							font-size: 14px;
							margin-left: 5px;
						}
					}
				}

				.skill-levels {
					.skill-level-item {
						margin-bottom: 15px;

						.skill-name {
							font-size: 14px;
							color: #333;
							margin-bottom: 8px;
						}

						.skill-slider-container {
							display: flex;
							align-items: center;

							slider {
								flex: 1;
							}

							.level-text {
								width: 45px;
								text-align: right;
								font-size: 14px;
								color: #5ac725;
							}
						}
					}
				}

				.summary-container {
					.summary-textarea {
						width: 100%;
						height: 120px;
						border: 1px solid #e5e5e5;
						border-radius: 4px;
						padding: 12px;
						font-size: 15px;
					}

					.word-count {
						text-align: right;
						font-size: 12px;
						color: #999;
						display: block;
						margin-top: 4px;
					}
				}
			}
		}

		.action-bar {
			flex: 1;

			.save-btn {
				width: 100%;
				height: 44px;
				line-height: 44px;
				background-color: #5ac725;
				color: #FFFFFF;
				font-size: 16px;
				font-weight: 500;
				border-radius: 22px;
			}
		}

		.bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 70px;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 20px;
			box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
			z-index: 9;
			gap: 30rpx;
		}

		.delete-action {
			.delete-btn {
				width: 100%;
				height: 44px;
				line-height: 44px;
				text-align: center;
				border-radius: 22px;
				font-size: 16px;
				color: #ff4d4f;
				background-color: #fff;
				border: 1px solid #ff4d4f;
			}
		}
	}
</style>